package com.muyi.biling.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.starmach.printsdk.BluetoothPrinterPort;
import com.starmach.printsdk.PrinterInstance;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.parceler.Parcels;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.muyi.biling.R;
import com.muyi.biling.bean.CommodityItem;
import com.muyi.biling.bean.OrderDetail;
import com.muyi.biling.bluetooth.BluetoothLeService;
import com.muyi.biling.bluetooth.DeviceScanActivity;
import com.muyi.biling.bluetooth.DeviceScanActivity_;
import com.muyi.biling.bluetooth.SampleGattAttributes;
import com.muyi.biling.util.Utils;

/**
 * Created by developer on 18-1-25.
 */

@SuppressLint("NewApi")
@EActivity(R.layout.activity_order_review)
public class OrderReviewActivity extends AppCompatActivity {

    private BluetoothLeService mBluetoothLeService;
    private boolean mPermissionTip = false;
    private static final int APP_PERMISSION = 100;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();

//            if (!TextUtils.isEmpty(mAddress)) {
//                if (mBluetoothLeService.initialize()) {
//                    mBluetoothLeService.connect(mAddress);
//                }
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                Toast.makeText(context, "蓝牙已连接", Toast.LENGTH_SHORT).show();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                Toast.makeText(context, "蓝牙未连接", Toast.LENGTH_SHORT).show();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            }
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 111) {
                sendData((String) msg.obj);
            }
        }
    };
    private PrinterInstance mPrinter;

    @ViewById(R.id.review_tv_state)
    TextView tvPortState;
    @ViewById(R.id.review_layout_state)
    LinearLayout layoutState;
    @ViewById(R.id.review_layout_chart)
    LinearLayout layoutGroup;
    @ViewById(R.id.review_layout_scroll)
    ScrollView layoutScroll;
    @ViewById(R.id.review_tv_custom)
    TextView tvCustom;
    @ViewById(R.id.review_tv_logistics)
    TextView tvLogistics;
    @ViewById(R.id.review_tv_seller)
    TextView tvSeller;
    @ViewById(R.id.review_tv_tip)
    TextView tvTip;
    @ViewById(R.id.review_tv_number)
    TextView tvNumber;
    @ViewById(R.id.review_tv_date)
    TextView tvDate;
    @ViewById(R.id.review_tv_sum)
    TextView tvSum;

    private int mWindowHeight;
    private OrderDetail mOrderDetail;

    @AfterInject
    void initDI() {

        Intent intent = getIntent();

        if (intent != null && intent.getExtras() != null) {
            mOrderDetail = Parcels.unwrap(intent.getParcelableExtra(OrderDetail.CLASS_NAME));
        }

    }

    @AfterViews
    void initView() {
        if (mOrderDetail != null
                && mOrderDetail.commodityList != null
                && mOrderDetail.commodityList.size() > 0) {
            tvCustom.setText(mOrderDetail.custom);
            tvLogistics.setText(mOrderDetail.logistics);
            tvSeller.setText(mOrderDetail.seller);
            tvTip.setText(mOrderDetail.tip);
            tvNumber.setText(mOrderDetail.number);
            tvDate.setText(mOrderDetail.date);
            tvSum.setText("合计：" + String.valueOf(mOrderDetail.sum) + "元");
            addTabRow();
        }
    }

    @Click(R.id.review_btn_connect)
    void toScanDevice() {
        Intent intent = new Intent(this, DeviceScanActivity_.class);
        startActivityForResult(intent, BluetoothLeService.RESULT_CODE);
    }

    @Click(R.id.review_btn_commit)
    void commitToPort() {
        checkPhoneState();

    }

    @Click(R.id.review_iv_back)
    void toEditPage() {
        finish();
    }

    private void addTabRow() {
        int margin = Utils.dp2px(1, this);
        int padding = Utils.dp2px(6, this);
        ArrayList<CommodityItem> dataList = mOrderDetail.commodityList;

        for (int i = 0; i < dataList.size(); i ++) {
            TableRow tableRow = new TableRow(this);
            tableRow.setBackgroundColor(Color.BLACK);
            CommodityItem commodityItem = dataList.get(i);

            for (int j = 0; j < 5; j ++) {
                TextView textView = new TextView(this);
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(17);
                textView.getPaint().setFakeBoldText(true);
                textView.setPadding(padding, padding, padding, padding);
                textView.setGravity(Gravity.CENTER);
                textView.setBackgroundColor(Color.WHITE);

                TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
                layoutParams.width = 0;
                layoutParams.height = TableRow.LayoutParams.MATCH_PARENT;

                switch (j) {
                    case 0:
                        textView.setText(commodityItem.title);
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 4;
                        break;
                    case 1:
                        textView.setText(String.valueOf(commodityItem.count));
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 1;
                        break;
                    case 2:
                        textView.setText(String.valueOf(commodityItem.unitPrice));
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 2;
                        break;
                    case 3:
                        textView.setText(String.valueOf(commodityItem.sumPrice));
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 2;
                        break;
                    case 4:
                        textView.setText(commodityItem.tip);
                        layoutParams.setMargins(margin, margin, margin, 0);
                        layoutParams.weight = 3;
                        break;
                }

                tableRow.addView(textView, layoutParams);
            }

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dp2px(70, this));

            layoutGroup.addView(tableRow, layoutParams);
        }

    }

    private Bitmap screenCurrentWindow(int h) {
        Display display = getWindowManager().getDefaultDisplay();
        View view = getWindow().getDecorView();
        //获取屏幕宽高
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int stateBarHeight = rect.top;
        int widths = display.getWidth();
        mWindowHeight = display.getHeight() - stateBarHeight;
        int height = 0;
        int startY = 0;
        if (h == 0 || h <= mWindowHeight) {
            height = mWindowHeight;
            startY = stateBarHeight;
        }else {
            height = h - mWindowHeight;
            startY = stateBarHeight + mWindowHeight - height;
        }

        //设置允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);

        //去掉状态栏高度
        Bitmap bitmap=Bitmap.createBitmap(
                view.getDrawingCache(),
                0,
                startY,
                widths,
                height);

        view.destroyDrawingCache();

        return bitmap;
    }

    public void screenWindow() {
        layoutState.setVisibility(View.GONE);
        layoutScroll.scrollTo(0 , 0);

        layoutScroll.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        int h = 0;
        for (int i = 0; i < layoutScroll.getChildCount(); i++) {
            h += layoutScroll.getChildAt(i).getMeasuredHeight();
        }

        Display display = getWindowManager().getDefaultDisplay();
        View view = getWindow().getDecorView();
        //获取屏幕宽高
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int stateBarHeight = rect.top;
        mWindowHeight = display.getHeight() - stateBarHeight;

        int screenCount = h / mWindowHeight;
        Bitmap bitmap;
        ArrayList<Bitmap> bitmaps = new ArrayList<>();
        int width = 0;
        int height = 0;

        if (screenCount > 0) {
            Bitmap bitmapTemp;
            for (int i = 1; i <= screenCount; i ++) {
                bitmapTemp = screenCurrentWindow(0);
                bitmaps.add(bitmapTemp);
                layoutScroll.scrollTo(0 , mWindowHeight * i + 2);
                width = bitmapTemp.getWidth();
                height += bitmapTemp.getHeight();
            }

            bitmapTemp = screenCurrentWindow(h % mWindowHeight + mWindowHeight);
            bitmaps.add(bitmapTemp);
            height += bitmapTemp.getHeight();

        }else {
            Bitmap bitmapTemp = screenCurrentWindow(0);
            bitmaps.add(bitmapTemp);
            width = bitmapTemp.getWidth();
            height += bitmapTemp.getHeight();
        }

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        int height2 = 0;
        for (int i = 0; i < bitmaps.size(); i ++) {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(bitmaps.get(i), 0, height2, null);
            height2 += bitmaps.get(i).getHeight();
        }

        if (bitmap != null) {
            try {
                // 获取内置SD卡路径
                String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                // 图片文件路径
                String filePath = sdCardPath + File.separator + "screenshot.bmp";
                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.flush();
                os.close();

                Message msg = new Message();
                msg.what = 111;
                msg.obj = filePath;
                handler.sendMessage(msg);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
//        mBluetoothLeService.disconnect();
//        unbindService(mServiceConnection);
//        unregisterReceiver(mGattUpdateReceiver);
        if (mPrinter != null && mPrinter.isConnected()) {
            mPrinter.closeConnection();
        }
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch(requestCode)
        {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if(!granted) {
                    mPermissionTip = false;
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(this, "请赋予存储卡权限后再试", Toast.LENGTH_SHORT).show();
                }else {
                    mPermissionTip = true;
                    screenWindow();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == BluetoothLeService.RESULT_CODE) {
            if (data.getExtras() != null) {
                String address = data.getStringExtra("address");

                BluetoothManager bluetoothManager =
                        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
                if (bluetoothManager == null) return;
                mPrinter = new BluetoothPrinterPort().btConnnect(this, address, bluetoothManager.getAdapter(), handler);

                tvPortState.setText("已连接");
                tvPortState.setTextColor(Color.parseColor("#00ffff"));

//                registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
//                Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
//                bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
            }

        }
    }

    @Background
    public void sendData(String filePath) {

        if (mPrinter == null) return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                layoutState.setVisibility(View.VISIBLE);
            }
        });

        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        mPrinter.ChineseModeChoice_Escpk((byte)0);
        mPrinter.setLf();
        mPrinter.printImage_Escpk(bitmap);
    }

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    private void checkPhoneState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {

                if (!mPermissionTip) {
                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                    requestPermissions(new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    }, APP_PERMISSION);
                }
            }else {
                if (!mPermissionTip) {
                    mPermissionTip = true;
                    screenWindow();
                }
            }
        }else {
            screenWindow();
        }
    }

}
